<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>设备功能</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="row-play">
      <div class="row-play-t">分类名：</div>
      <el-autocomplete
          v-model="searchForm.categoryName"
          :fetch-suggestions="querySearchAsyncCategoryName"
          placeholder="请输入内容"
          size="mini"
          style="width: 160px;margin-right: 10px;"
          :maxlength="15"
          show-word-limit
      ></el-autocomplete>
      <div class="row-play-t">设备名：</div>
      <el-autocomplete
          v-model="searchForm.deviceName"
          :fetch-suggestions="querySearchAsyncDeviceName"
          placeholder="请输入内容"
          size="mini"
          style="width: 160px;margin-right: 10px;"
          :maxlength="15"
          show-word-limit
      ></el-autocomplete>
      <div class="row-play-t">版本：</div>
      <el-autocomplete
          v-model="searchForm.deviceVersion"
          :fetch-suggestions="querySearchAsyncDeviceVersion"
          placeholder="请输入格式：x.x.x"
          size="mini"
          style="width: 160px;margin-right: 10px;"
          :maxlength="15"
          show-word-limit
      ></el-autocomplete>
      <div class="row-play-t">功能：</div>
      <el-autocomplete
          v-model="searchForm.name"
          :fetch-suggestions="querySearchAsyncFunctionName"
          placeholder="请输入内容"
          size="mini"
          style="width: 160px;margin-right: 10px;"
          :maxlength="15"
          show-word-limit
      ></el-autocomplete>
      <div class="row-play-t">状态：</div>
      <el-select class="row-play-p" v-model="searchForm.status" placeholder="请选择" size="mini"
                 style="width: 100px;margin-right: 10px;">
        <el-option
            v-for="item in statusList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
        </el-option>
      </el-select>
      <el-button @click="getPage" size="mini">搜索</el-button>
      <el-button @click="add" size="mini">新增</el-button>
      <el-button @click="toggleSelection()" size="mini">取消选择</el-button>
      <el-button @click="deleteMany" size="mini" type="danger">批量删除</el-button>
    </div>
    <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange">
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column
          label="修改时间"
          width="180">
        <template slot-scope="scope">{{ scope.row.updateTime }}</template>
      </el-table-column>
      <el-table-column
          label="功能名称"
          width="200">
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top">
            <p>创建人：{{ scope.row.createUserName }}</p>
            <p>创建时间: {{ scope.row.createTime }}</p>
            <p>修改人: {{ scope.row.updateUserName }}</p>
            <p>修改时间: {{ scope.row.updateTime }}</p>
            <div slot="reference" class="name-wrapper">
              <el-tag size="medium">{{ scope.row.name }}</el-tag>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column
          label="设备名称"
          width="120">
        <template slot-scope="scope">
          {{ scope.row.deviceName }}
        </template>
      </el-table-column>
      <el-table-column
          label="版本号"
          width="100">
        <template slot-scope="scope">
          {{ scope.row.deviceVersion }}
        </template>
      </el-table-column>
      <el-table-column
          label="分类名称"
          width="120">
        <template slot-scope="scope">
          {{ scope.row.categoryName }}
        </template>
      </el-table-column>
      <el-table-column
          label="状态"
          width="100">
        <template slot-scope="scope">
          <el-switch
              @change="editStatus(scope.row)"
              style="display: block;height: 30px;"
              v-model="scope.row.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <div class="row-play">
            <el-popover trigger="hover" placement="top">
              <p style="max-width: 200px">{{ scope.row.detail }}</p>
              <div slot="reference" class="name-wrapper">
                <el-tag class="row-play-p" size="medium">详情</el-tag>
              </div>
            </el-popover>
            <el-button
                size="mini"
                @click="edit(scope.row)">编辑
            </el-button>
            <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.row)">删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 40]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalSize">
      </el-pagination>
    </div>
    <el-dialog title="新增功能" :visible.sync="dialogAddFormVisible">
      <el-form ref="formRef" :model="addForm" :rules="formRules">
        <el-form-item label="分类名称" :label-width="formLabelWidth" style="width: 400px">
          <el-autocomplete
              v-model="addForm.categoryName"
              :fetch-suggestions="querySearchAsyncCategoryName"
              placeholder="请输入内容"
              size="mini"
              style="width: 160px;margin-right: 10px;"
              :maxlength=maxlength
              :minlength=minlength
              show-word-limit
          ></el-autocomplete>
        </el-form-item>
        <el-form-item label="设备名称" :label-width="formLabelWidth" style="width: 400px">
          <el-autocomplete
              v-model="addForm.deviceName"
              :fetch-suggestions="querySearchAsyncDeviceName"
              placeholder="请输入内容"
              size="mini"
              style="width: 160px;margin-right: 10px;"
              :maxlength=maxlength
              :minlength=minlength
              show-word-limit
          ></el-autocomplete>
        </el-form-item>
        <el-form-item label="版本号" :label-width="formLabelWidth" style="width: 400px">
          <el-autocomplete
              v-model="addForm.deviceVersion"
              :fetch-suggestions="querySearchAsyncDeviceVersion"
              placeholder="请输入版本号：x.x.x"
              size="mini"
              style="width: 160px;margin-right: 10px;"
              :maxlength=maxlength
              :minlength=minlength
              show-word-limit
          ></el-autocomplete>
        </el-form-item>
        <el-form-item label="功能名称" :label-width="formLabelWidth" style="width: 400px" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入内容" size="mini"></el-input>
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth">
          <el-select v-model="addForm.status" size="mini"
                     style="width: 100px;" disabled>
            <!--            <el-option label="上线" :value="1"></el-option>-->
            <el-option label="下线" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="详情" :label-width="formLabelWidth" style="width: 500px">
          <el-input
              type="textarea"
              placeholder="请输入内容"
              v-model="addForm.detail"
              maxlength="100"
              show-word-limit
              size="mini"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogAddFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addFunction">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="编辑功能" :visible.sync="dialogEditFormVisible">
      <el-form ref="formRef" :model="editForm" :rules="formRules">
        <el-form-item label="分类名称" :label-width="formLabelWidth" style="width: 400px">
          <el-autocomplete
              v-model="editForm.categoryName"
              :fetch-suggestions="querySearchAsyncCategoryName"
              placeholder="请输入内容"
              size="mini"
              style="width: 160px;margin-right: 10px;"
              :maxlength=maxlength
              :minlength=minlength
              show-word-limit
          ></el-autocomplete>
        </el-form-item>
        <el-form-item label="设备名称" :label-width="formLabelWidth" style="width: 400px">
          <el-autocomplete
              v-model="editForm.deviceName"
              :fetch-suggestions="querySearchAsyncDeviceName"
              placeholder="请输入内容"
              size="mini"
              style="width: 160px;margin-right: 10px;"
              :maxlength=maxlength
              :minlength=minlength
              show-word-limit
          ></el-autocomplete>
        </el-form-item>
        <el-form-item label="版本号" :label-width="formLabelWidth" style="width: 400px">
          <el-autocomplete
              v-model="editForm.deviceVersion"
              :fetch-suggestions="querySearchAsyncDeviceVersion"
              placeholder="请输入版本号：x.x.x"
              size="mini"
              style="width: 160px;margin-right: 10px;"
              :maxlength=maxlength
              :minlength=minlength
              show-word-limit
          ></el-autocomplete>
        </el-form-item>
        <el-form-item label="功能名称" :label-width="formLabelWidth" style="width: 400px" prop="version">
          <el-input v-model="editForm.name" placeholder="请输入内容" size="mini"></el-input>
        </el-form-item>
        <el-form-item label="详情" :label-width="formLabelWidth" style="width: 500px">
          <el-input
              type="textarea"
              placeholder="请输入内容"
              v-model="editForm.detail"
              maxlength="100"
              show-word-limit
              size="mini"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogEditFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editFunction">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      maxlength: 15,
      minlength: 1,
      statusList: [{
        value: 0,
        label: '下线'
      }, {
        value: 1,
        label: '在线'
      }, {
        value: null,
        label: ''
      }],
      tableData: [],
      multipleSelection: [],
      currentPage: 1,
      pageSize: 10,
      totalSize: 0,
      dialogAddFormVisible: false,
      dialogEditFormVisible: false,
      formLabelWidth: '120px',
      addForm: {
        name: '',
        deviceVersion: '',
        deviceName:'',
        status: 0,
        categoryName: '',
        detail:null
      },
      searchForm: {
        name: '',
        deviceVersion: '',
        deviceName:'',
        status: null,
        categoryName: ''
      },
      editForm: {
        id: null,
        name: '',
        deviceVersion: '',
        deviceName:'',
        categoryName: '',
        status:null,
        detail:null
      },
      formRules: {
        name: [{required: true, message: '请输入功能名称', trigger: 'blur'},
          {min: 1, max: 15, message: '长度在一到十五个字符之间', trigger: 'blur'}]
      },
      restaurants: [],
      categoryNameList: [],
      deviceNameList: [],
      deviceVersionList: [],
      functionNameList:[],
      customHeaders: {
        Token: window.sessionStorage.getItem('token')
      }
    }
  },
  methods: {
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该功能, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(async () => {
        const {data: res} = await this.$http.delete("/function/" + row.id);
        if (res.code === 0) {
          return this.$message.error(res.msg);
        }
        await this.getPage();
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getPage();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getPage();
    },
    async getPage() {
      const {data: res} = await this.$http.get("/function/page", {
        params: {
          page: this.currentPage,
          pageSize: this.pageSize,
          name: this.searchForm.name,
          status:this.searchForm.status,
          deviceName:this.searchForm.deviceName,
          deviceVersion: this.searchForm.deviceVersion,
          categoryName: this.searchForm.categoryName
        }
      });
      if (res.code === 0) {
        return this.$message.error("获取设备分类信息失败");
      }
      this.tableData = res.data.records;
      this.totalSize = res.data.total;
      await this.getCategoryNameList();
      await this.getDeviceNameVersionList();
      await this.getFunctionNameList();
    },
    async editStatus(row) {
      this.$refs.multipleTable.doLayout();
      const {data: res} = await this.$http.put("/function/updateStatus", {
        id: row.id,
        status: row.status
      });
      if (res.code === 0) {
        await this.getPage();
        return this.$message.error(res.msg);
      }
      this.$message({
        type: 'success',
        message: '修改成功!'
      });
    },
    deleteMany() {
      let ids = [];
      this.multipleSelection.forEach(row => {
        ids.push(row.id);
      })
      let idss = ids.join(',');
      this.$confirm('此操作将永久删除多个功能, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(async () => {
        const {data: res} = await this.$http.delete("/function", {
          params: {
            ids: idss
          }
        });
        if (res.code === 0) {
          return this.$message.error(res.msg);
        }
        await this.getPage();
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    add() {
      this.dialogAddFormVisible = true;
    },
    addFunction() {
      this.$refs.formRef.validate(async valid => {
        if (!valid) return false;
        this.dialogAddFormVisible = false;
        const {data: res} = await this.$http.post("/function/add", this.addForm);
        if (res.code === 0) {
          return this.$message.error(res.msg);
        }
        this.$message.success("添加成功");
        await this.getPage();
      })
    },
    edit(row) {
      this.editForm.id = row.id;
      this.editForm.name = row.name;
      this.editForm.deviceVersion = row.deviceVersion;
      this.editForm.categoryName = row.categoryName;
      this.editForm.deviceName = row.deviceName;
      this.editForm.status = row.status;
      this.editForm.detail=row.detail;
      this.dialogEditFormVisible = true;
    },
    editFunction() {
      this.$refs.formRef.validate(async valid => {
        if (!valid) return false;
        this.dialogEditFormVisible = false;
        const {data: res} = await this.$http.put("/function/edit", this.editForm);
        if (res.code === 0) {
          return this.$message.error(res.msg);
        }
        this.$message.success("编辑成功");
        await this.getPage();
      })
    },
    querySearchAsyncCategoryName(queryString, callback) {
      var categoryNameList = this.categoryNameList;
      var results = queryString ? categoryNameList.filter(this.createStateFilter(queryString)) : categoryNameList;
      callback(results);
    },
    querySearchAsyncDeviceName(queryString, callback) {
      var deviceNameList = this.deviceNameList;
      var results = queryString ? deviceNameList.filter(this.createStateFilter(queryString)) : deviceNameList;
      callback(results);
    },
    querySearchAsyncDeviceVersion(queryString, callback) {
      var deviceVersionList = this.deviceVersionList;
      var results = queryString ? deviceVersionList.filter(this.createStateFilter(queryString)) : deviceVersionList;
      callback(results);
    },
    querySearchAsyncFunctionName(queryString, callback) {
      var functionNameList = this.functionNameList;
      var results = queryString ? functionNameList.filter(this.createStateFilter(queryString)) : functionNameList;
      callback(results);
    },
    createStateFilter(queryString) {
      return (state) => {
        return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    async getCategoryNameList() {
      const {data: res} = await this.$http.get("/category/nameList");
      if (res.code === 0) {
        return this.$message.error(res.msg);
      }
      this.categoryNameList = res.data;
    },
    async getDeviceNameVersionList() {
      const {data: res} = await this.$http.get("/device/nameVersionList");
      if (res.code === 0) {
        return this.$message.error("获取设备名和设备版本失败");
      }
      if (res.data !== null) {
        this.deviceNameList = res.data.nameSet;
        this.deviceVersionList = res.data.versionSet;
      }
    },
    async getFunctionNameList() {
      const {data: res} = await this.$http.get("/function/nameList");
      if (res.code === 0) {
        return this.$message.error("获取功能名称失败");
      }
      if (res.data !== null) {
        this.functionNameList = res.data;
      }
    }
  },
  mounted() {
    this.getPage();
  }
}
</script>

<style lang="less" scoped>
.row-play {
  display: flex;
  align-items: center;

  .row-play-p {
    margin-right: 20px;
  }

  .row-play-t {
    font-size: 1px;
  }
}

.block {
  text-align: center;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

  :hover {
    border-color: #409EFF;
  }
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>